import fs from "fs-extra";
import chalk from "chalk";
import getNpmPackageVersion from "get-npm-package-version";
import { ncp } from "ncp";
import { resolveApp } from "../scripts/resolve";
import packageJson from "../package.json";
import download from "download-git-repo";

ncp.limit = 16;
process.stdin.setEncoding("utf8");

export function createProject(projectName, template = "react", noverify) {
	if (!noverify) {
		// 验证版本
		updateWarning();
	}
	checkProjectExist(projectName);
	download(
		`direct:git@gitlab.seeyon.com:a9/code/frontend/tools/templates/${template}-app.git`,
		projectName,
		{ clone: true },
		function (err) {
			if (err) {
				console.error(
					chalk.red(
						`初始化项目失败，请确认本地已正常配置SSH密钥，且有【读取】 git@gitlab.seeyon.com:a9/code/frontend/tools/templates/${template}-app.git 仓库的权限，或者联系管理员。`,
					),
				);
			} else {
				console.log(chalk.green("初始化项目成功"));
			}
		},
	);
}

function checkProjectExist(projectName) {
	if (fs.existsSync(resolveApp(projectName))) {
		console.log(
			`${chalk.yellow(`${chalk.blue(projectName)} 已经存在于当前目录。`)}`,
		);
		process.exit(1);
	}
}

function updateWarning() {
	const lastestVersion = getNpmPackageVersion("@seeyon/syf");
	if (lastestVersion && lastestVersion !== packageJson.version) {
		console.log(
			`${chalk.blue("@seeyon/syf")} 当前版本为 ${packageJson.version}`,
		);
		console.log(
			`${chalk.blue("@seeyon/syf")} 有最新版本 ${chalk.yellow(
				lastestVersion,
			)} 请及时更新!`,
		);
		process.exit(1);
	}
}
